package com.ittable.tdcqfdmeo.serivice.impl;

import com.ittable.tdcqfdmeo.serivice.handler.UserServerHandler;
import com.lagou.rpcdemo.common.JSONSerializer;
import com.lagou.rpcdemo.common.RpcDecoder;
import com.lagou.rpcdemo.common.RpcEncoder;
import com.lagou.rpcdemo.request.RpcRequest;
import com.lagou.rpcdemo.service.UserService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author srh
 * @date 2020/10/18
 **/
@Service
public class UserServiceImpl implements UserService {

    @Value("${host}")
    private String host;
    @Value("${port}")
    private Integer port;
    @Resource
    private UserServerHandler userServerHandler;

    @Override
    public String sayHello(String word) {
        System.out.println("server accept message = " + word);
        return word + " : success";
    }

    @PostConstruct
    public void init() {
        startServer(host, port);
    }

    private void startServer(String host, int port) {
        try {
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(bossGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                            pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                            pipeline.addLast(userServerHandler);
                        }
                    });

            bootstrap.bind(host, port);

        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
